package com.jt.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import com.jt.pojo.Item;
import com.jt.service.DubboCartService;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.QEncoderStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author 张琪
 * @date 2020/12/16
 * @describe
 */
@Service(timeout = 3000)
public class DubboCartServiceImpl implements DubboCartService {

    @Autowired
    private CartMapper cartMapper;


    public void deleteCart(Cart cart) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("item_id", cart.getItemId());
        cartMapper.delete(queryWrapper);
    }


    /**
     * 如果用户重复加购, 则只做数量的修改
     *
     * @param cart
     */
    @Override
    @Transactional
    public void saveCart(Cart cart) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("item_id", cart.getItemId());
        Cart cart1 = cartMapper.selectOne(queryWrapper);
        if (cart1 == null) {
//            数据库中没有数据时, 直接插入数据
            cartMapper.insert(cart);
        } else {
//
            int num = cart1.getNum() + cart.getNum();
//            1. 手写SQL
            Cart cartTemp = new Cart().setNum(num).setId(cart1.getId());
//            2. 简洁封装
            cartMapper.updateById(cartTemp);
        }
    }

    /*
        sql: update tb_cart set num = #{num}, updated = #{updated}
                where user_id = #{userId} and item_id = #{itemId}
     */

    @Override
    @Transactional
    public void updateCartNum(Cart cart) {
        /* 因为在mp中, update()操作中, 会跟据传入的update的非空值, 更新数据库中的对应数据, 因此需要修改Cart对象的值*/

        Cart cart1 = new Cart();

        cart1.setNum(cart.getNum());
//        根据传入的参数设置构造器     在cart表中, 需要通过 user_id 和 item_id 同时来确定一条数据, 这样才能正确根性数据,
//        这两个属性也称为联合主键
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("user_id", cart.getUserId());
        updateWrapper.eq("item_id", cart.getItemId());

        cartMapper.update(cart1, updateWrapper);
    }

    @Override
    public List<Cart> findAllCartById(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        List<Cart> list = cartMapper.selectList(queryWrapper);
        return list;
    }
}
